package com.base.service.client;
import com.base.bean.*;
import com.base.dao.*;

import java.sql.Timestamp;
import java.util.*;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import tool.ClientTool;
import tool.TimeTool;


/**
 * 注意：准备替换ClientService  但是ClientService类不要删除
 * 使用了session的 都手动finally块中close
 * @author chz
 * 
 *
 */

public class AdvanceClientService {
	private ClientBaseDao cbd;
	private ClientExtendDao ced;
	private ClientPhoneDao cpd;
	private ClientXattrDao cxd;
	private UserDao ud;

	
	
	// 单例模式 start
	private volatile static AdvanceClientService instance = null;	
	
	private AdvanceClientService() {
		this.cbd= (ClientBaseDao) _BaseDao.ac.getBean("ClientBaseDao");
		this.ced= (ClientExtendDao) _BaseDao.ac.getBean("ClientExtendDao");
		this.cpd= (ClientPhoneDao) _BaseDao.ac.getBean("ClientPhoneDao");
		this.cxd= (ClientXattrDao) _BaseDao.ac.getBean("ClientXattrDao");
		this.ud = (UserDao) _BaseDao.ac.getBean("UserDao");
	}
	
	public static AdvanceClientService getInstance() {
		if (instance == null) {
			synchronized (AdvanceClientService.class) {// 1
				if (instance == null) {// 2
					instance = new AdvanceClientService();// 3
				}
			}
		}
		return instance;
	}
	// 单例模式 end
	
	
	
	public static void main(String[] args){
		AdvanceClientService instance=AdvanceClientService.getInstance();
		int r= instance.allotByPhone("18381133788",36,true);  //更改客户分配人(创建人也修改了 不然无法修改)
//		int r= instance.allotByPhone("15982079516", 36,false);  //更改客户分配人(不修改创建人)
//		int r= instance.batChangeStateByOwner(1, 1);  //批量分配
		System.out.println(r);  //13608276824
		
		//int result=instance.checkPhone("15982079516");
		
		
		/*
		// 查询测试 start
		ClientQueryFormBean query=new ClientQueryFormBean();
		
		query.setPhone("");		// 若有电话存在
		query.setOwner(1);
		query.setProvince("");
		query.setCity("");
		query.setName("");
		query.setCrmFlag(0);
		
		System.out.println(instance.getTotal(query));
		
		
		
		List<ClientFormBean> beans =instance.getDetailByCidList(instance.QueryCidList(query, 0, 10));	//获取总数

		for(ClientFormBean bean:beans){
//			instance.filter(bean);
			
			System.out.print(bean.getCb().getProvince()+"/");
			System.out.print(bean.getCb().getCity()+"/");
			System.out.print(bean.getCb().getArea()+"/");
			System.out.print(bean.getCb().getName()+"/");
			
			System.out.print(bean.getCe().getClientType()+"/");
			
			if(bean.getPhones()!=null){
				for(ClientPhone p:bean.getPhones()){
					System.out.print(p.getPhone()+"/");
				}
			}
			
			System.out.print(bean.getCb().getState()+"/");
			System.out.print(bean.getCe().getState()+"/");
			
			System.out.print(bean.getOwner()+"/");
			System.out.print(bean.getOwnName());
			System.out.print(bean.getCb().getCid()+"/");
			System.out.println();
		}
		
		// 查询测试 end
		
//		instance.changeState(60426, 2);
		*/
	}
	
	
	
	//########################################################################
	/**
	 * 
	 * @param owner
	 * @param state
	 * @return
	 */
	public int getTotal(Integer owner,Integer state){
		
		Session session=null;
	try{	
		session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Query query = session.getNamedQuery("com.base.bean.clientbase.getTotal");
		query.setInteger("owner", owner);
		query.setInteger("state", state);
		
		Object cnt = query.uniqueResult();  
		session.getTransaction().commit();
		if(cnt != null){  
		    return Integer.parseInt(cnt.toString());  
		}else 
			return 0;	
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	

	/**
	 * 将某电话对应客户 分配给某人
	 * @param phone
	 * @param owner
	 * @return
	 */
	public int allotByPhone(String phone,Integer owner,boolean isChangeCreator){
		Session session=null;
	try{	
		session = this.cpd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Query query = session.getNamedQuery("com.base.bean.clientphone.getCidByPhone");
		query.setString("phone", phone);
		
		
		Integer cid = Integer.parseInt(query.uniqueResult().toString());  // 异常就返回0
		
		
		
		
		// 更改所属人
		String hqlUpdate = "";
		int updatedEntities = 0;
		hqlUpdate = "update ClientPhone p set p.owner = :owner where p.cid= :cid";
		// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
		updatedEntities = session.createQuery( hqlUpdate )
		        .setInteger( "owner",owner)
		        .setInteger( "cid",cid)	        
		.executeUpdate();	
		
		if(isChangeCreator){
			
			hqlUpdate = "update ClientBase  p set p.owner = :owner,p.creator=:creator,p.modified= :modified where p.cid= :cid";
			updatedEntities = updatedEntities + session.createQuery( hqlUpdate )
					.setInteger( "owner",owner)		
					.setInteger( "creator",owner)
					.setTimestamp("modified", TimeTool.getCurrentTime())
			        .setInteger( "cid",cid)	          
			.executeUpdate();
		}else{
			hqlUpdate = "update ClientBase  p set p.owner = :owner,p.creator=:creator,p.modified= :modified where p.cid= :cid";
			updatedEntities = updatedEntities + session.createQuery( hqlUpdate )
					.setInteger( "owner",owner)		
			        .setInteger( "cid",cid)	          
			.executeUpdate();
		}
		
		
		hqlUpdate = "update ClientExtend  p set p.owner = :owner where p.cid= :cid";
		updatedEntities = updatedEntities +session.createQuery( hqlUpdate )
				.setInteger( "owner",owner)
		        .setInteger( "cid",cid)	  
		.executeUpdate();
		
		session.getTransaction().commit();
		
		return updatedEntities;
	}catch(Exception e){
		e.printStackTrace();
		session.beginTransaction().rollback();
		return 0;
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	
	public List<ClientBase> getListByPage(Integer owner,int state,int offset,int pageSize){
		Session session=null;
	try{	
		session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Query query = session.getNamedQuery("com.base.bean.clientbase.getListByPage");
		query.setInteger("owner", owner);
		query.setInteger("state", state);
		
		query.setInteger("offset", offset);
		query.setInteger("pageSize", pageSize);
		List<ClientBase> list = (List<ClientBase>)query.list();  
		session.getTransaction().commit();
		if(list != null){  
		    return list;  
		}else 
			return null;	
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	public ClientFormBean getDetailByPhone(String phone){
		ClientFormBean bean=new ClientFormBean(0);
		
		if(!ClientTool.isMobileNO(phone)){
			bean.setState(-1);	// pattern error
			bean.setTip("手机号码格式错误（ " +phone+" )");
		}
		else{
			List<ClientPhone> _cps0 = this.cpd.findByHql("from ClientPhone p where p.phone ='"+phone+"'");
			if(_cps0.size()>0){
				bean.setState(1);
				bean.setTip("");
				try{
				bean.setCid(_cps0.get(0).getCid());
				
				List<ClientBase> _cbs = this.cbd.findByHql("from ClientBase cb where cb.cid="+bean.getCid());
				List<ClientExtend> _ces = this.ced.findByHql("from ClientExtend ce where ce.cid="+bean.getCid());
				List<ClientPhone> _cps = this.cpd.findByHql("from ClientPhone cp where cp.cid="+bean.getCid());
				List<ClientXattr> _cxs = this.cxd.findByHql("from ClientXattr cx where cx.cid="+bean.getCid());
				
				if(_cbs.size()>0){
					if(_cbs.size()>1){
						bean.setState(-4);
						bean.setTip("该电话对应了多个客户，请联系管理员（"+phone+")");
						return bean;	//此情况跳出
					}
					bean.setCb(_cbs.get(0));
					
				}
				if(_ces.size()>0)
					bean.setCe(_ces.get(0));
				if(_cps.size()>0)
					bean.setPhones(_cps);
				if(_cxs!=null)
					bean.setCx(_cxs.get(0));
				
				
				}catch(Exception e){
					e.printStackTrace();
					bean.setState(-3);
					bean.setTip("出现其他异常,请联系管理员("+phone+")");
				}
				
			}
			else{
				bean.setState(-2);	// can't find
				bean.setTip("该电话号码不存在与系统( "+phone+" )");
			}
			
		}
		
		return bean;
	}
	
	/**
	 *  处理数据用
	 *  @deprecated
	 * @param offset
	 * @param pageSize
	 * @return
	 */
	public List<ClientPhone> getPhoneIdByPage(int offset,int pageSize){
		return this.cpd.findByPage("from ClientPhone cp where cp.state<>2 order by created", offset, pageSize);
			
	}
	
	/**
	 * 动态查询 采用拼接sql方式
	 * @param clientQueryForm
	 * @param offset
	 * @param pageSize
	 * @return
	 */
	public List<Integer> QueryCidList(ClientQueryFormBean clientQueryForm,int offset,int pageSize){
		
		StringBuffer condition = new StringBuffer();
		String sql = "";
		
		Session session=null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		
		
		if(!clientQueryForm.getPhone().equals("")){		//查询条件包含手机号码
			
			if(ClientTool.isMobileNO(clientQueryForm.getPhone())){	//是完整电话号码
				sql = " select a.cid from client_phone a  where a.state<>2 #CONDITION#  limit #OFFSET#,#PAGESIZE# ";
				condition.append(" and a.phone = "+clientQueryForm.getPhone());
			}else{	//不是完整电话
				sql = " select a.cid from client_base a INNER join client_phone b  on a.cid=b.cid and b.state<>2 #CONDITION#  limit #OFFSET#,#PAGESIZE# ";	
				condition.append(" and b.phone like '%"+clientQueryForm.getPhone()+"%' ");
				if(clientQueryForm.getOwner()>0)
					condition.append(" and a.owner = "+clientQueryForm.getOwner());	
				if(clientQueryForm.getState()>0)
					
					condition.append(" and a.state = "+clientQueryForm.getState());	
				if(!clientQueryForm.getArea().equals(""))
					condition.append(" and b.area like '%"+clientQueryForm.getArea()+"%'");
				if(!clientQueryForm.getCity().equals(""))
					condition.append(" and a.city like '%"+clientQueryForm.getCity()+"%'");
				if(!clientQueryForm.getProvince().equals(""))
					condition.append(" and a.province like '%"+clientQueryForm.getProvince()+"%'");
				
				if(!clientQueryForm.getName().equals(""))
					condition.append(" and a.name like '%"+clientQueryForm.getName()+"%'");
				
				if(clientQueryForm.getCrmFlag()>0)
					condition.append(" and a.crmFlag ="+clientQueryForm.getCrmFlag());
			}
			
			
			
		}else{		//查询条件不包含手机号码
		
			sql = " select a.cid from client_base a INNER join client_extend b on a.cid=b.cid #CONDITION# limit #OFFSET#,#PAGESIZE# ";
			
			if(clientQueryForm.getOwner()>0)
				condition.append(" and a.owner = "+clientQueryForm.getOwner());
			
			if(!clientQueryForm.getArea().equals(""))
				condition.append(" and a.area like '%"+clientQueryForm.getArea()+"%'");
			if(!clientQueryForm.getCity().equals(""))
				condition.append(" and a.city like '%"+clientQueryForm.getCity()+"%'");
			if(!clientQueryForm.getProvince().equals(""))
				condition.append(" and a.province like '%"+clientQueryForm.getProvince()+"%'");
			
			if(!clientQueryForm.getName().equals(""))
				condition.append(" and a.name like '%"+clientQueryForm.getName()+"%'");
			
			if(clientQueryForm.getCrmFlag()>0)
				condition.append(" and a.crmFlag ="+clientQueryForm.getCrmFlag());
		}
		
		
		sql=sql.replace("#CONDITION#", condition);
		sql=sql.replace("#OFFSET#", new Integer(offset).toString());
		sql=sql.replace("#PAGESIZE#", new Integer(pageSize).toString());
		
//		System.out.println(sql);

		return session.createSQLQuery(sql).list();
	}finally{
		if(session.isOpen())
			session.close();
	}
		
		
		/* 内连接实例
		
		select a.*,b.* from client_base a INNER join client_extend b 
		on a.cid=b.cid  limit 5,5
		
		.createSQLQuery(sql)
		
		String hql="select order.id, sum(price.amount), count(item)
					from Order as order
					    join order.lineItems as item
					    join item.product as product,
					    Catalog as catalog
					    join catalog.prices as price
					where order.paid = false
					    and order.customer = :customer
					    and price.product = product
					    and catalog = :currentCatalog
					group by order
					having sum(price.amount)
					> :minAmount
					order by sum(price.amount) desc"
		*/
		
		
	
	
	}
	
	
	public List<ClientFormBean> getDetailByCidList(List<Integer> cidList){
		List<ClientFormBean> beanList=new ArrayList<ClientFormBean>();
		for(Integer cid:cidList){
			ClientFormBean bean = new ClientFormBean();
			List<ClientBase> _cbs = this.cbd.findByHql("from ClientBase cb where cb.cid="+cid);
			List<ClientExtend> _ces = this.ced.findByHql("from ClientExtend ce where ce.cid="+cid);
			List<ClientPhone> _cps = this.cpd.findByHql("from ClientPhone cp where cp.state<>2 and cp.cid="+cid); //排除作废电话号码
			List<ClientXattr> _cxs = this.cxd.findByHql("from ClientXattr cx where cx.cid="+cid);
			List<User> _users = null;
			
			if(_cbs.size()>0){
				bean.setCb(_cbs.get(0));
				_users = this.ud.findByHql("from User u where u.uid="+bean.getCb().getOwner());
			}
			if(_ces.size()>0)
				bean.setCe(_ces.get(0));
			if(_cps.size()>0)
				bean.setPhones(_cps);
			if(_cxs.size()>0)
				bean.setCx(_cxs.get(0));
			if(_users.size()>0)
				bean.setOwnName(_users.get(0).getTruename());
			
			bean.setOwner(bean.getCb().getOwner());
			bean.setState(bean.getCb().getState());
			beanList.add(bean);
		}
		
		
		return beanList;
	}
	
	/**
	 * 条件查询获取总数
	 * @param clientQueryForm
	 * @return
	 */
	public int getTotal(ClientQueryFormBean clientQueryForm){
		StringBuffer condition = new StringBuffer();
		String sql = "";
		
		Session session=null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		
		
		if(!clientQueryForm.getPhone().equals("")){		//查询条件包含手机号码
			
			if(ClientTool.isMobileNO(clientQueryForm.getPhone())){	//是完整电话号码
				sql = " select count(*) from client_phone a  where a.state<>2 #CONDITION# ";
				condition.append(" and a.phone = "+clientQueryForm.getPhone());
			}else{	//不是完整电话
				sql = " select count(*)  from client_base a INNER join client_phone b  on a.cid=b.cid and b.state<>2 #CONDITION# ";	
				condition.append(" and b.phone like '%"+clientQueryForm.getPhone()+"%' ");
				if(clientQueryForm.getOwner()>0)
					condition.append(" and a.owner = "+clientQueryForm.getOwner());	
				if(clientQueryForm.getState()>0)
					
					condition.append(" and a.state = "+clientQueryForm.getState());	
				if(!clientQueryForm.getArea().equals(""))
					condition.append(" and b.area like '%"+clientQueryForm.getArea()+"%'");
				if(!clientQueryForm.getCity().equals(""))
					condition.append(" and a.city like '%"+clientQueryForm.getCity()+"%'");
				if(!clientQueryForm.getProvince().equals(""))
					condition.append(" and a.province like '%"+clientQueryForm.getProvince()+"%'");
				
				if(!clientQueryForm.getName().equals(""))
					condition.append(" and a.name like '%"+clientQueryForm.getName()+"%'");
			}
			
			
			
		}else{		//查询条件不包含手机号码
		
			sql = " select count(*) from client_base a INNER join client_extend b on a.cid=b.cid #CONDITION# ";
			
			if(clientQueryForm.getOwner()>0)
				condition.append(" and a.owner = "+clientQueryForm.getOwner());
			
			if(!clientQueryForm.getArea().equals(""))
				condition.append(" and a.area like '%"+clientQueryForm.getArea()+"%'");
			if(!clientQueryForm.getCity().equals(""))
				condition.append(" and a.city like '%"+clientQueryForm.getCity()+"%'");
			if(!clientQueryForm.getProvince().equals(""))
				condition.append(" and a.province like '%"+clientQueryForm.getProvince()+"%'");
			
			if(!clientQueryForm.getName().equals(""))
				condition.append(" and a.name like '%"+clientQueryForm.getName()+"%'");
			
			if(clientQueryForm.getCrmFlag()>0)
				condition.append(" and a.crmFlag ="+clientQueryForm.getCrmFlag());
		}
		
		
		sql=sql.replace("#CONDITION#", condition);
	
		return  Integer.parseInt(session.createSQLQuery(sql).uniqueResult().toString());
		
//		return ((Integer) session.createSQLQuery(sql).iterate().next()).intValue();
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	
	/**
	 * 新增客户 事务处理
	 * @param bean
	 * @return
	 */
	public ClientFormBean add(ClientFormBean bean){
		int r_checkName=0;
		try {
			r_checkName = ClientTool.isName(bean.getCb().getName());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			r_checkName=3;
		}
		bean.setState(0);
		
		switch(r_checkName){
		case 1:
			bean.setTip("姓名出现非汉字");
			bean.setState(-1);
			break;
		case 2:
			bean.setTip("姓名中出现称呼");
			bean.setState(-1);
			break;
		case 3:
			bean.setTip("检查姓名出现异常");
			bean.setState(-1);
			break;
		}
		
		
		if(this.checkName(bean.getCb().getName())<=0){
			bean.setState(-1);
			bean.setTip("姓名验证未能通过");		
		}
		
		if(bean.getState()<0)
			return bean;
		
		
		Timestamp now = TimeTool.getCurrentTime();
		
			
		Session session = null;
		Transaction tx = null ;

		
		try{session = this.cbd.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			Timestamp _time=TimeTool.getCurrentTime();
			ClientBase cb=bean.getCb();
			cb.setCreated(_time);
			cb.setModified(_time);
			cb.setCreated(now);
			cb.setModified(now);
			cb.setState(1);
			cb.setShareCode("");
			session.save(cb);	
			
			ClientExtend ce=bean.getCe();
			ce.setCreated(_time);
			
			
			
			
			// 查询max cid
			@SuppressWarnings("unchecked")
			List<Integer> results = session
					.createCriteria(ClientBase.class)
					.setMaxResults(1)
					.setProjection(
							Projections.projectionList().add(
									Projections.max("cid"))

					).list();
			
			
			Integer cid = results.get(0);
			bean.setCid(cid);
			
			
			if(cid==null){
				bean.setState(-3);
				bean.setTip("新增失败");
				return bean;
			}
			
			ce.setCid(cid);
			ce.setCreated(now);
			ce.setModified(now);
			ce.setState(1);
			session.save(ce);
			
			ClientXattr cx=bean.getCx();
			if(cx==null)
				cx=new ClientXattr();
			
			
			cx.setCid(cid);
			cx.setState(1);
			session.save(cx);	
			
			
			List<ClientPhone> cps = bean.getPhones();
			boolean phoneRepeat=false;
			int count=0;
			
			for(ClientPhone p: cps){
				// 查询电话是否已经存在
				count = Integer.parseInt(session.createSQLQuery("SELECT count(*) FROM client_phone cp  WHERE cp.phone= :phone")
						.setString("phone", p.getPhone())
						.uniqueResult().toString());
				
				if(count>0)
					phoneRepeat=phoneRepeat || true;
				else{
					p.setCid(cid);
					p.setCreated(now);
					p.setState(1);
					session.save(p);
				}
//				System.out.println("###:"+count);
						
			}
			
			System.out.println("repeat:"+phoneRepeat);
			if(!phoneRepeat){   // 未重复
				bean.setState(1);
				bean.setTip("success");
			}else{
				System.out.println("电话重复");
				bean.setState(-3);
				bean.setTip("电话重复");
				throw new Exception("phone repeat");
			}
		
			tx.commit();
			return bean;
			
		}catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			bean.setState(-2);
			if(bean.getTip().equals(""))
				bean.setTip("出现异常，请联系管理员");
			return bean;

		} finally {
			if(session.isOpen())
				session.close();
		}
	}
	
	
	
	/** 备注：客户拥有者离职，flag是否也要更改状态，另外这部分客户 到底是统一给某人还是 均分给相应区域的销售员？
	 *  批量将某销售员的客户标记为某个状态（主要用于离职销售人员）返回值为修改了多少个销售员 
	 * @param owner
	 * @param state 最好标记状态>10 以免和正常状态混淆
	 * @return 修改的记录数（）
	 */
	public int batChangeStateByOwner(Integer owner,int state){
		Session session = null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		String hqlUpdate = "";
		int updatedEntities= 0;
		
		hqlUpdate = "update ClientBase p set p.state= :state  where p.owner = :owner";
		// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
		updatedEntities = updatedEntities + session.createQuery( hqlUpdate )
		        .setInteger( "owner",owner)
		        .setInteger( "state",state)
		.executeUpdate();	
		
		
		hqlUpdate = "update ClientExtend p set p.state= :state  where p.owner = :owner";
		// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
		session.createQuery( hqlUpdate )
		        .setInteger( "owner",owner)
		        .setInteger( "state",state)
		.executeUpdate();
		
		hqlUpdate = "update ClientPhone p set p.state= :state  where p.owner = :owner";
		// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
		session.createQuery( hqlUpdate )
		        .setInteger( "owner",owner)
		        .setInteger( "state",state)
		.executeUpdate();
		
		session.getTransaction().commit();
		
		return updatedEntities;
		
	}catch(Exception e){
		e.printStackTrace();
		session.beginTransaction().rollback();
		return 0;
	}finally{
		if(session.isOpen())
			session.close();
	}
		
	}
	
	
	/**
	 *  作废某电话 作废的者是谁没有记录？
	 * @deprecated
	 * @param phone
	 * @return
	 */
	public int wastePhone(String phone){
		Session session = null;
		try{
			session = this.cpd.getSessionFactory().getCurrentSession();
			Transaction tx = session.beginTransaction();
			String hqlUpdate = "update ClientPhone p set p.state = 2 ,p.phone= :phone2, p.wasted = :wasted where p.phone = :phone";
			// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
			int updatedEntities = session.createQuery( hqlUpdate )
			        .setString( "phone",phone)
			        .setString( "phone2","#"+phone)
			        .setTimestamp("wasted", TimeTool.getCurrentTime())
			.executeUpdate();	
			tx.commit();
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}finally{
			if(session.isOpen())
				session.close();
		}
	}
	
	
	
	
	
	/** 此修改方法过时
	 * 更改姓名客户以及所属人（老客户 CRMFlag=1）
	 * @deprecated
	 * @param name
	 * @param phone
	 * @param owner
	 * @return
	 */
	public int modify(String name,String phone,Integer owner){
		ClientQueryFormBean queryBean=new ClientQueryFormBean();
		queryBean.setPhone(phone);
		List<Integer> cids = this.QueryCidList(queryBean, 0, 10);
		if(cids.size()>1)
			return cids.size();
		Timestamp now =TimeTool.getCurrentTime();
		
		ClientFormBean bean=this.getDetailByCid(cids.get(0));
		bean.getCb().setName(name);
		bean.getCb().setOwner(owner);
		bean.getCb().setModified(now);
		
		List<ClientPhone> cps=bean.getPhones();
		for(int i=0;i<cps.size();i++){
			if(bean.getPhones().get(i).getPhone().equals(phone)){
				bean.getPhones().get(i).setCreated(now);
			}
		}
		
		bean.getCe().setOwner(owner);
		this.modify(bean);
		return 1;
		
	}
	
	
	/**
	 * 客户修改：事务处理, 修改前必须是先将对象从数据库中取出来 再更新  
	 * @param bean
	 * @return
	 */
	public ClientFormBean modify(ClientFormBean bean){
	
		if(bean.getCid()<1){	// 缺少cid
			bean.setState(-2);
			bean.setTip("修改时缺乏对应的记录");
			return bean;
		}
		
		Timestamp _time=TimeTool.getCurrentTime();
		
		ClientFormBean _bean = this.getDetailByCid(bean.getCid());	
		ClientBase cb = bean.getCb();
		ClientExtend ce = bean.getCe();
		ClientXattr cx = bean.getCx();
		if(cx==null)
			cx=new ClientXattr();
		
		ClientBase _cb = _bean.getCb();
		ClientExtend _ce = _bean.getCe();
		ClientXattr _cx = _bean.getCx();
		
		Session session = null;
		Transaction tx = null ;
		
		try{session = this.cbd.getSessionFactory().getCurrentSession();
			
			tx = session.beginTransaction();		
			cb.setModified(_time);
			cb.setCid(_cb.getCid());
			session.merge(cb);
			
			ce.setCid(bean.getCid());
		    ce.setModified(_time);
			ce.setId(_ce.getId());
			session.merge(ce);
			
			
			if(_cx!=null){
				System.out.println("####"+_cx.getId());
				cx.setId(_cx.getId());
				cx.setCid(bean.getCid());
				session.merge(cx);
			}

			
			List<ClientPhone> cps = bean.getPhones();
			List<ClientPhone> _cps = _bean.getPhones();
			
			boolean phoneRepeat = false;
			
			for(int i=0;i<cps.size();i++){
				
				if(cps.get(i).getId()==null)		// 新增
					cps.get(i).setId(0);
				
				if(cps.get(i).getId()<0){	// 电话作废的操作
					cps.get(i).setId(_cps.get(i).getId());
					cps.get(i).setCreated(_cps.get(i).getCreated());
					cps.get(i).setCid(Math.abs(_cps.get(i).getCid()));
					cps.get(i).setState(2);
					cps.get(i).setPhone("#"+cps.get(i).getPhone());
					cps.get(i).setWasted(_time);
					session.merge(cps.get(i));
				}else if(cps.get(i).getId()==0){	//add phone 电话新增需要查询是否已有电话
					int count = 0;
					// 查询电话是否已经存在
					count = Integer.parseInt(session.createSQLQuery("SELECT count(*) FROM client_phone cp  WHERE cp.phone= :phone")
							.setString("phone", cps.get(i).getPhone())
							.uniqueResult().toString());
					if(count>0){
						phoneRepeat = phoneRepeat || true;
					}
					cps.get(i).setCreated(_time);
					cps.get(i).setState(1);
					cps.get(i).setCid(bean.getCb().getCid());
					session.save(cps.get(i));
				}else if(cps.get(i).getId()>0)	//电话不变
					continue;
			}
			
			if(phoneRepeat){
				bean.setState(-2);
				bean.setTip("电话重复");
				throw new Exception("phone repeat");
				
			}
			
			tx.commit();
			bean.setState(1);
			bean.setTip("操作成功");
			return bean;
			
		}catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			bean.setState(-2);
			if(bean.getTip().equals(""))
				bean.setTip("出现异常，请联系管理员");
			return bean;

		} finally {
			if(session.isOpen())
				session.close();
		}
	}
	
	/** 更改状态 用update的方式处理更好
	 * @deprecated
	 * @param cid
	 * @param state
	 * @return
	 */
	public int changeState(Integer cid,Integer state){
		Timestamp now = TimeTool.getCurrentTime();
		Session session = null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		ClientFormBean bean=this.getDetailByCid(cid);
		ClientBase cb=bean.getCb();
		if(cb!=null){
			cb.setState(state);
			session.merge(cb);
		}
		ClientExtend ce= bean.getCe();	
		if(ce!=null){
			ce.setState(state);
			session.merge(ce);
		}
		List<ClientPhone> cps = bean.getPhones(); 
		if(cps.size()>0){
			for(ClientPhone p:cps){
				p.setState(state);
				if(state==2)
					p.setWasted(now);
				session.merge(p);
			}
		}
		
		tx.commit();
		
		return 1;
		
	}finally {
			session.close();
		}
		
		
		        
	}
	
	
	public String listConvertJson(List<ClientFormBean> clientList) {
		return null;
	}
	
	public ClientFormBean getDetailByCid(Integer cid){
		ClientFormBean bean =  new ClientFormBean();
		List<ClientBase> _cbs = this.cbd.findByHql("from ClientBase cb where cb.cid="+cid);
		List<ClientExtend> _ces = this.ced.findByHql("from ClientExtend ce where ce.cid="+cid);
		List<ClientPhone> _cps = this.cpd.findByHql("from ClientPhone cp where cp.state<>2 and cp.cid="+cid);
		List<ClientXattr> _cxs = this.cxd.findByHql("from ClientXattr cx where cx.cid="+cid);
		
		if(_cbs.size()>0){
			bean.setCb(_cbs.get(0));
			bean.setOwner(bean.getCb().getOwner());
			bean.setState(bean.getCb().getState());
			
		}
		if(_ces.size()>0)
			bean.setCe(_ces.get(0));
		if(_cps.size()>0)
			bean.setPhones(_cps);
		if(_cxs.size()>0)
			bean.setCx(_cxs.get(0));
		
		
		return bean;
	}
	
	
	

	
	
	public int checkPhone(String phone){
		
		if(!ClientTool.isMobileNO(phone))
			return -1;
		
		Session session=null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Query query = session.getNamedQuery("com.base.bean.clientphone.check");
		query.setString("phone", phone);
		
		
		Object cnt = query.uniqueResult();  
		session.getTransaction().commit();
		if(cnt != null){  
		    return Integer.parseInt(cnt.toString());
		   
		}else 
			return 0;	
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	public int checkName(String name){
	try{
		int r= ClientTool.isName(name);
		if(r>0)
			return -2 ;
		else 
			return 1;
	}catch(Exception e){
		e.printStackTrace();
		return -1;
	}
	}
	
	public int checkNameCity(String name,String cityId){
	try{
		if(ClientTool.isName(name)!=0)	
			return -1;
	}catch(Exception e){
		e.printStackTrace();
		return -2;
	}
		
		Session session=null;
	try{session = this.cbd.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Query query = session.getNamedQuery("com.base.bean.clientbase.checkCityName");
		query.setString("name", name);
		query.setString("cityId", cityId);
		
		Object cnt = query.uniqueResult();  
		session.getTransaction().commit();
		if(cnt != null){  
		    return Integer.parseInt(cnt.toString());  
		}else 
			return 0;
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	
	
	
	public ClientFormBean filter(ClientFormBean client){
		
		ClientFormBean bean=new ClientFormBean();
		bean.getCb().setName(ClientTool.vagueName(client.getCb().getName()));
		
		for(int i=0;i<client.getPhones().size();i++){
			client.getPhones().get(i).setPhone(ClientTool.vaguePhone(client.getPhones().get(i).getPhone()));
		}
		bean.setPhones(client.getPhones());
		
		return bean;
	}
	
	
	
	
	
	
	//#####################################################################################
	
	public ClientBaseDao getCbd() {
		return cbd;
	}
	public void setCbd(ClientBaseDao cbd) {
		this.cbd = cbd;
	}
	public ClientExtendDao getCed() {
		return ced;
	}
	public void setCed(ClientExtendDao ced) {
		this.ced = ced;
	}
	public ClientPhoneDao getCpd() {
		return cpd;
	}
	public void setCpd(ClientPhoneDao cpd) {
		this.cpd = cpd;
	}
	public ClientXattrDao getCxd() {
		return cxd;
	}
	public void setCxd(ClientXattrDao cxd) {
		this.cxd = cxd;
	}

	

	
	
	
	
	

}
